package leet.ku._36;

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[][] trans = translate(board);
        for (int i = 0; i < 9; i++) {
        	if (!isValidRow(trans, i))
        		return false;
        	if (!isValidColumn(trans, i))
        		return false;
        }
        for (int i = 0; i < 3; i++)
        	for (int j = 0; j < 3; j++)
        		if (!isValidCell(trans, i, j))
        			return false;
        return true;
    }
    
    private boolean isValidCell(int[][] board, int cellRow, int cellColumn) {
    	cellRow *= 3;
    	cellColumn *= 3;
    	boolean[] check = new boolean[9];
    	for (int i = 0; i < 3; i++)
    		for (int j = 0; j < 3; j++) {
        		if (board[cellRow + i][cellColumn + j] < 0)
        			continue;
        		if (check[board[cellRow + i][cellColumn + j]])
        			return false;
        		check[board[cellRow + i][cellColumn + j]] = true;
        	}
    			
		return true;
	}

	private int[][] translate(char[][] board) {
    	int[][] result = new int[9][9];
    	for (int i = 0; i < 9; i++)
    		for (int j = 0; j < 9; j++)
    			if (board[i][j] == '.')
    				result[i][j] = -1;
    			else
    				result[i][j] = board[i][j] - '1';
    	return result;
    }
    
    private boolean isValidRow(int[][] board, int row) {
    	boolean[] check = new boolean[9];
    	for (int i = 0; i < 9; i++) {
    		if (board[row][i] < 0)
    			continue;
    		if (check[board[row][i]])
    			return false;
    		check[board[row][i]] = true;
    	}
    	return true;
    }
    
    private boolean isValidColumn(int[][] board, int column) {
    	boolean[] check = new boolean[9];
    	for (int i = 0; i < 9; i++) {
    		if (board[i][column] < 0)
    			continue;
    		if (check[board[i][column]])
    			return false;
    		check[board[i][column]] = true;
    	}
    	return true;
    }
}